<template>
  <div>
    <FormPanel ref="from" :list="formList" @formChange="changeHandle" :isSubmitBtn="false" :collapse="false" :labelWidth="190"></FormPanel>
    <FilterTable ref="table" :columns="columns" :dataSource="tableList" height="auto" :isSelectColumn="false" :onColumnsChange="columns => (this.columns = columns)">
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" @click="addHandle()" icon="el-icon-plus">新 增</multiuse-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="isaddCar" :title="'新增车辆'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <selectCar :carData="carData" @close="carcloseHandler" />
    </BaseDialog>

    <BaseDialog :visible.sync="isDiscount" :title="'折扣详情'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <DiscountDetail :rowData="DiscountData" @close="Discountclose" />
    </BaseDialog>

    <div style="height:47px;"></div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDrawer(1)">关 闭</el-button>
      <multiuse-button type="primary" :click="closeDrawer.bind(this, 2)" :disabled="ischange">提 交</multiuse-button>
      <multiuse-button type="primary" :click="closeDrawer.bind(this, 3)" :disabled="ischange">保 存</multiuse-button>
    </div>
  </div>
</template>
<script>
import { savePlan1, getLoginUser, queryDealerAddress } from '@/api/dealerSale/salesPlan/PlanReportSideB/index.js';
import { dictionary } from '@/utils/dictMixin';
import Cookies from 'js-cookie';
import DiscountDetail from './DiscountDetail';
import UploadCropper from '@/components/UploadCropper';
import selectCar from './selectCar';
import moment from 'moment';
export default {
  data() {
    this.saveData = null;
    return {
      formList: this.createdFrom(),
      columns: this.createdTable(),
      tableList: [],
      addressList: [],
      isaddCar: false,
      carData: {},
      isDiscount: false,
      DiscountData: {},
      dealerCode: Cookies.get('ownerCode'),
      ischange: false,
      quantity: 0,
      imgPaths: []
    };
  },
  components: {
    DiscountDetail,
    UploadCropper,
    selectCar
  },
  created() {
    this.getDealerAddress();
  },
  mounted() {
    this.table = this.$refs.table.$refs.pageTable;
  },
  mixins: [dictionary],
  methods: {
    createdFrom() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '订单信息'
        },
        {
          type: 'INPUT',
          label: '计划编号',
          fieldName: 'plan1No',
          disabled: true
        },
        {
          type: 'DATE',
          label: '计划年月',
          fieldName: 'planYearAndMonth',
          disabled: true,
          dateType: 'month',
          initialValue: moment().add(1,'months').format('YYYY-MM'),
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          disabled: true
        },
         {
          type: 'INPUT',
          label: '数量',
          fieldName: 'quantity',
          disabled: true,
          editType: 'number'
        },
        {
          type: 'BREAK_SPACE',
          label: '车辆信息'
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 120,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 1)}>
                  删除
                </multiuse-button>
              </div>
            );
          }
        },

        {
          title: '物料编码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '物料描述',
          dataIndex: 'productName',
          align: 'center',
          width: 400,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '数量',
          dataIndex: 'planNum',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'number',
          width: 100,
          editRequired: true,
          editPattern: /^[1-9]\d*$/,
          defaultEditable: true,
          rules: [{ required: true, message: '请填写正整数', trigger: 'blur' }],
          onInput: (index, data) => {
            this.changeNum(index, data);
          }
        },
         {
          title: '是否打保证金',
          dataIndex: 'isMargin',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: p => {
            return (
              <el-select
                size="mini"
                v-model={p.row.isMargin}
                onChange={value => {
                  p.row.isMargin = value;
                }}
              >
                {p.row.isMarginList.map(item => (
                  <el-option key={item.value} label={item.text} value={item.value} />
                ))}
              </el-select>
            );
          }
        },
         {
          title: '打款凭证',
          dataIndex: 'discountTotalAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: p => {
            return (
              <span class="discount" onClick={() => this.editHandle(p.row, 2)}>
                {p.row.discountTotalAmount}
              </span>
            );
          }
        },
         {
          title: '收车地址',
          dataIndex: 'addressId',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: p => {
            return (
              <el-select
                size="mini"
                v-model={p.row.addressId}
                placeholder="请选择"
                onChange={value => {
                  p.row.addressId = value;
                  this.changeDealerAddress(value,p.row);
                }}
              >
                {p.row.addressList.map(item => (
                  <el-option key={item.value} label={item.text} value={item.value} />
                ))}
              </el-select>
            );
          }
        },
        {
          title: '联系人',
          dataIndex: 'linkMan',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '送达城市',
          dataIndex: 'deliveryCityName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
         {
          title: '联系方式',
          dataIndex: 'linkPhone',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '备注',
          dataIndex: 'remark',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          defaultEditable: true,
          editType: 'text'
        },
        {
          title: '市场指导价',
          dataIndex: 'oemDirectivePrice',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'input'
        },
        
        {
          title: '车系名称',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型名称',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
         {
          title: '配置',
          dataIndex: 'configName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '选装',
          dataIndex: 'optionName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '内饰',
          dataIndex: 'trimColorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
      ];
    },
    changeValueNum(a) {
      if (!a || a == null || isNaN(a)) {
        return 0;
      } else {
        return a;
      }
    },
    // 修改收车地址
    changeDealerAddress(value,row) {
      for (let address of this.addressList) {
        if(address.addressId == value) {
          row.address = address.address;
          row.deliveryCityName = address.cityName;
          row.linkMan = address.linkMan;
          row.linkPhone = address.linkPhone;
          return;
        }
      }
    },
    // 新增车辆
    addHandle() {
      this.$refs.from.SUBMIT_FORM();
      if (this.saveData) {
        let json = JSON.parse(JSON.stringify(this.saveData));
        json.dealerCode = this.dealerCode;
        this.carData = json;
        this.isaddCar = true;
        this.saveData = null;
      }
    },
    changeHandle(val) {
      this.saveData = val;
    },
    //更改车辆信息列表
    changeList(list) {
      var count = 0;
      this.tableList.map(x => {
        count = Number(x.planNum) + Number(count);
      });
      this.quantity = count;
      
      this.formList[4].initialValue = count;  
      // console.log(this.formList,'fromList');
    },
    async getDealerAddress() {
      let loginuser = await getLoginUser();
      let res = await queryDealerAddress();
      let dataList = res.data.addressDTOS;
      this.addressList = dataList;
      this.formList[3].initialValue = loginuser.data.orgName;
    },
    async closeDrawer(type) {
      if (type == 1) {
        //1 关闭
        this.$emit('close');
      } else if (type == 2) {
        //2 提交
        if (this.tableList.length < 1) {
          this.$notify({
            title: '警告',
            message: '请选择车辆',
            type: 'warning'
          });
          return;
        }
        this.$refs.from.SUBMIT_FORM();
        if (this.saveData) {

          let json = JSON.parse(JSON.stringify(this.saveData));
          let itemList = this.tableList;
          let is = false;
          itemList.map(x => {
            if (Number(x.planNum) > 10000000000 || Number(x.planNum) < 1) {
              is = true;
            }
          });
          if (is) {
            this.$notify({
              title: '警告',
              message: '输入数量过大或过小',
              type: 'warning'
            });
            return;
          }
          
          json.dealerCode = this.dealerCode;
          json.planStatus = 21031002;
          json.quantity = this.quantity;
          json.planMonth = json.planYearAndMonth.split('-')[1];
          json.planYear = json.planYearAndMonth.split('-')[0];
          json.detailList = itemList;
          
          this.addPlan1(json,'提交成功');
        }
      } else {
        //3 保存
        if (this.tableList.length < 1) {
          this.$notify({
            title: '警告',
            message: '请选择车辆',
            type: 'warning'
          });
          return;
        }
        this.$refs.from.SUBMIT_FORM();
        if (this.saveData) {
          let json = JSON.parse(JSON.stringify(this.saveData));
          let itemList = this.tableList;
          let is = false;
          itemList.map(x => {
            if (Number(x.planNum) > 10000000000 || Number(x.planNum) < 1) {
              is = true;
            }
          });
          if (is) {
            this.$notify({
              title: '警告',
              message: '输入数量过大或过小',
              type: 'warning'
            });
            return;
          }

          json.dealerCode = this.dealerCode;
          json.planStatus = 21031001;
          json.quantity = this.quantity;
          json.planMonth = json.planYearAndMonth.split('-')[1];
          json.planYear = json.planYearAndMonth.split('-')[0];
          json.detailList = itemList;

          this.addPlan1(json,'保存成功');

        }
      }
    },
    async addPlan1(data,tag) {
      //  console.log(data,'提交数据');
      
       let res = await savePlan1(data);
          if (res.resultCode == 200) {
            this.$notify({
              title: '成功',
              message: tag,
              type: 'success'
            });
            this.$emit('close', data);
          } else {
            this.saveData = null;
          }
    },

    async carcloseHandler(carData) {
        if(carData) {
          let str = false;

          let adderssList = this.addressList.map(x => ({
            text: `${x.address}${x.addressProperty == 60351001 ? '(主店)' : ''}`,
            value: x.addressId,
            addressProperty: x.addressProperty
          }));
          adderssList.map(x => {
            if (!str && x.addressProperty == 60351001) {
                str = x.value;
              }
            });

          carData.forEach(car => {

            car.addressId = str ? str : adderssList[0].value;
            this.changeDealerAddress(car.addressId,car);

            car.isMargin = 10041002;
            car.isMarginList =  [{ text: '否', value: 10041002 },{ text: '是', value: 10041001 }];
            car.addressList = adderssList;
         
            this.table.EXECUTE_INSERT([car]);
          });

        }
        this.isaddCar = false;
    },
    Discountclose() {
      this.isDiscount = false;
    },
    //改变数量
    changeNum(index, data) {
      let num = '';
      let str = '';
      for (let i in index) {
        num = index[i];
        // console.log(i, 'i');
        str = i.split('|')[0];
      }
      let Rep = /^[1-9]\d*$/;
      if (num > 10000000000) {
        this.$notify({
          title: '警告',
          message: '输入数量过大',
          type: 'warning'
        });
        return;
      }
      // console.log(num, Rep.test(num));
      if (Rep.test(num)) {
        this.changeList(this.tableList);
      }
    },
    async editHandle(data, type) {
      if (type == 1) {
        await this.$confirm('是否确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            this.table.EXECUTE_DELETE([data]);
            // console.log(this.tableList, '删除了');
            this.changeList(this.tableList);
          })
          .catch(() => {});
      } else {
        this.DiscountData = data;
        this.isDiscount = true;
      }
    },
    formatNumber(val) {
      return Number(val).toFixed(2);
    },
    successHandler(val) {
      this.form.imgPaths = val;
    }
  }
};
</script>
<style lang="less">
.discount {
  text-decoration: underline;
  color: #d1291a;
  cursor: pointer;
}
</style>
